package cmd

import (
	"api/controllers"
	"github.com/labstack/echo"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"io/ioutil"
	"os"
	"path/filepath"
	"strconv"
	"time"
)

// 创建server子命令
var serverCmd = &cobra.Command{
	Use:   "server",
	Short: "Run server",
	Long:  `Run server.`,
	// server子命令的实现，启动应用服务
	Run: func(cmd *cobra.Command, args []string) {
		e := echo.New()

		e.SetDebug(viper.GetBool("server.debug"))

		initEchoLog(e)

		e.SetHTTPErrorHandler(controllers.HttpErrorHandler)

		addMiddlewares(e)

		addRoutes(e)

		pid := os.Getpid()
		err := ioutil.WriteFile(filepath.Join(viper.GetString("dir.data"), viper.GetString("server.pid_file")), []byte(strconv.Itoa(pid)), 0644)
		if err != nil {
			e.Logger().Error(err)
		} else {
			e.Logger().Info("server pid ", pid)
		}

		addr := viper.GetString("server.listen_addr")
		e.Logger().Info("server listening on ", addr)
		e.Run(standard.WithConfig(engine.Config{
			Address:      addr,
			ReadTimeout:  5 * time.Second,
			WriteTimeout: 10 * time.Second,
		}))
	},
}

func init() {
	// 绑定server子命令特有的命令行参数，root命令里绑定的参数对server子命令也可用
	serverCmd.Flags().StringP("server.listen_addr", "l", "", "server listen address")

	viper.BindPFlags(serverCmd.PersistentFlags())

	viper.BindPFlags(serverCmd.Flags())

	// ...
}

// 初始化Echo框架日志打印
func initEchoLog(e *echo.Echo) {
	// ...
}

// 添加需要的中间件
func addMiddlewares(e *echo.Echo) {
	// ...
}

// 添加路由
func addRoutes(e *echo.Echo) {
	// ...
}
